const {
  get,post
} = require("../../utils/request")
const bgMusic = wx.getBackgroundAudioManager()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isOpen: false, //播放开关
    starttime: '00:00', //正在播放时长
    duration: '', //总时长
    obj: {},
    imgList: [],
    isAuto: 'false',
    language:'',
    routeId:'',
    offset:0,
    max:1
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad(options) {
    this.setData({
      isAuto: options.isAuto,
      language: options.language,
      routeId:options.routeId
    })
    get('/scenic/area/getScenicAreaInfo', {
      id: options.id
    }).then(res => {
      console.log(res,'res');
      this.setData({
        obj: res,
        duration: this.formatTime(res.audioList[0].time),
        imgList: res.images && res.images.split(',') || []
      })
    })
  },
  //点击轮播图预览
  previewImg(e) {
    let src = e.currentTarget.dataset.src
    let list = e.currentTarget.dataset.list
    wx.previewImage({
      urls: list,
      current: src
    })
  },
  //点击查看位置
  viewLocationFn() {
    wx.navigateBack({
      delta: 1
    })
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('someEvent', {
      lat: this.data.obj.latitude,
      log: this.data.obj.longitude
    });
  },
  changeFn(e) {
    let type = e.currentTarget.dataset.type
    if (type == 'next') {
      get('/scenic/area/getNext',{id: this.data.obj.id,routeId: this.data.routeId}).then(res => {
        this.setData({
          obj: res,
          duration: this.formatTime(res.audioList[0].time),
          imgList: res.images && res.images.split(',') || [],
          isOpen: false,
          starttime: '00:00',
          offset: 0
        })
        this.listenerButtonStop()
      })
    }else{
      get('/scenic/area/getPrior',{id: this.data.obj.id,routeId: this.data.routeId}).then(res => {
        this.setData({
          obj: res,
          duration: this.formatTime(res.audioList[0].time),
          imgList: res.images && res.images.split(',') || [],
          isOpen: false,
          starttime: '00:00',
          offset: 0
        })
        this.listenerButtonStop()
      })
    }
  },
  // 播放
  listenerButtonPlay: function () {
    post('/scenic/area/incPlayCount?id='+this.data.obj.id)
    var that = this
    //bug ios 播放时必须加title 不然会报错导致音乐不播放
    bgMusic.title = this.data.obj.scenicName
    bgMusic.epname = this.data.obj.scenicName
    bgMusic.coverImgUrl = this.data.obj.images
    bgMusic.src = this.data.obj.audioList[0].url;
    bgMusic.onTimeUpdate(() => {
      var currentTime = parseInt(bgMusic.currentTime);
      var min = "0" + parseInt(currentTime / 60);
      var max = parseInt(bgMusic.duration);
      var sec = currentTime % 60;
      if (sec < 10) {
        sec = "0" + sec;
      };
      var starttime = min + ':' + sec; /*  00:00  */
      that.setData({
        offset: currentTime,
        starttime: starttime,
        max: max,
        changePlay: true
      })
    })
    //播放结束
    bgMusic.onEnded(() => {
      if(that.data.isAuto == 'true'){
        wx.startLocationUpdate({
          success() {
            const _locationChangeFn = function(res) {
              //可以得到经纬度
              get('/scenic/area/getLatestScenic',{scenicId: that.data.obj.scenicId,longitude: res.longitude,latitude: res.latitude,language: that.data.language,routeId: that.data.routeId || 0}).then(res => {
                that.setData({
                  obj: res,
                  duration: that.formatTime(res.audioTime),
                  imgList: res.imageUrl && res.imageUrl.split(',') || []
                },()=>{
                  that.autolistenerButtonPlay()
                })
              })
              wx.offLocationChange(_locationChangeFn)
            }
            wx.onLocationChange(_locationChangeFn)
          },
          fail() {
            wx.showToast({
              title: '使用自动播放功能请手动打开定位权限',
              icon:'none'
            })
           }
          })
      }
      that.setData({
        starttime: '00:00',
        isOpen: false,
        offset: 0
      })
    })
    bgMusic.play();
    that.setData({
      isOpen: true,
    })
  },
  // 自动播放
  autolistenerButtonPlay: function () {
    post('/scenic/area/incPlayCount?id='+this.data.obj.id)
    var that = this
    //bug ios 播放时必须加title 不然会报错导致音乐不播放
    bgMusic.title = this.data.obj.scenicName
    bgMusic.epname = this.data.obj.scenicName
    bgMusic.src = this.data.obj.audioUrl;
    bgMusic.onTimeUpdate(() => {
      var currentTime = parseInt(bgMusic.currentTime);
      var min = "0" + parseInt(currentTime / 60);
      var max = parseInt(bgMusic.duration);
      var sec = currentTime % 60;
      if (sec < 10) {
        sec = "0" + sec;
      };
      var starttime = min + ':' + sec; /*  00:00  */
      that.setData({
        offset: currentTime,
        starttime: starttime,
        max: max,
        changePlay: true
      })
    })
    //播放结束
    bgMusic.onEnded(() => {
      if(that.data.isAuto == 'true'){
        wx.startLocationUpdate({
          success() {
            const _locationChangeFn = function(res) {
              //可以得到经纬度
              get('/scenic/area/getLatestScenic',{scenicId: that.data.obj.scenicId,longitude: res.longitude,latitude: res.latitude,language: that.data.language,routeId: that.data.routeId || 0}).then(res => {
                that.setData({
                  obj: res,
                  duration: that.formatTime(res.audioTime),
                  imgList: res.imageUrl && res.imageUrl.split(',') || []
                },()=>{
                  that.autolistenerButtonPlay()
                })
              })
              wx.offLocationChange(_locationChangeFn)
            }
            wx.onLocationChange(_locationChangeFn)
          },
          fail() {
            wx.showToast({
              title: '使用自动播放功能请手动打开定位权限',
              icon:'none'
            })
           }
          })
      }
      that.setData({
        starttime: '00:00',
        isOpen: false,
        offset: 0
      })
    })
    bgMusic.play();
    that.setData({
      isOpen: true,
    })
  },
  //暂停播放
  listenerButtonPause() {
    var that = this
    bgMusic.pause()
    that.setData({
      isOpen: false,
    })
  },
  listenerButtonStop() {
    bgMusic.stop()
  },
  // 进度条拖拽
  sliderChange(e) {
    var that = this
    var offset = parseInt(e.detail.value);
    bgMusic.play();
    bgMusic.seek(offset);
    that.setData({
      isOpen: true,
    })
  },
  formatTime(value) {
    var secondTime = parseInt(value) // 秒
    var minuteTime = 0 // 分
    var result = ''
    if (secondTime < 60) {
      result = '00:' + (secondTime > 9 ? secondTime : '0' + secondTime);
    } else {
      minuteTime = parseInt(secondTime / 60)
      secondTime = parseInt(secondTime % 60)
      let minute = minuteTime > 9 ? minuteTime : '0' + minuteTime;
      let second = secondTime > 9 ? secondTime : '0' + secondTime;
      result = minute + ':' + second;
    }
    return result;
  },
  // 页面卸载时停止播放
  onUnload() {
    var that = this
    that.listenerButtonStop() //停止播放
  },


  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})